package com.maxlen.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maxlen.common.utils.Constant;
import com.maxlen.common.utils.CopyUtils;
import com.maxlen.common.utils.PageUtils;
import com.maxlen.common.utils.Query;
import com.maxlen.goods.dao.BrandDao;
import com.maxlen.goods.entity.BrandEntity;
import com.maxlen.goods.entity.dto.SkuItemDTO;
import com.maxlen.goods.entity.vo.BrandVO;
import com.maxlen.goods.service.BrandService;
import com.maxlen.goods.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<BrandEntity> wrapper = new LambdaQueryWrapper<>();
        String key = params.get(Constant.KEY) == null ? null : params.get(Constant.KEY).toString();
        if(StringUtils.hasText(key)) {
            wrapper.like(BrandEntity::getName, key).or()
                    .like(BrandEntity::getBrandId, key).or()
                    .like(BrandEntity::getDescript, key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void add(BrandVO brandVO) {
        BrandEntity brand = CopyUtils.copy(brandVO, BrandEntity.class);
        baseMapper.insert(brand);
    }

    @Override
    @Transactional
    public void updateDetail(BrandVO brandVO) {
        BrandEntity brand = CopyUtils.copy(brandVO, BrandEntity.class);
        baseMapper.updateById(brand);
        if(StringUtils.hasText(brandVO.getName())){
            categoryBrandRelationService.updateBrand(brandVO.getBrandId(), brandVO.getName());
        }
    }

    @Override
    @Transactional
    public void removeDetail(List<Long> brandIds) {
        baseMapper.deleteBatchIds(brandIds);

        // 删除商品和分类关联的信息
        categoryBrandRelationService.removeBatchByBrandId(brandIds);
    }

}
